﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Web.SystemConfig.Services;
using Web.SystemConfig.DataAccess;
using Microsoft.Web.UI.WebControls;
using System.Web.UI.WebControls;
using System.Web;
using DreamBuilder.Common;
using DreamBuilder.Core.Message;


namespace Web.SystemConfig.Business
{
    public class BUSAuth_Org : BusinessBase, IAuth_Org
    {
        public BUSAuth_Org()
        {
            dal = new DALAuth_Org();
        }       


        #region IAuth_Org 成员

        public string CheckDeptParentId(string parrentId)
        {
            DataTable dt = dal.CheckDeptParentId(parrentId);
            string parentid = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                parrentId = dt.Rows[0][0].ToString();
            }
            return parrentId;
        }

        /// <summary>
        /// 通过ORG_ID 获取部门信息
        /// </summary>
        /// <returns></returns>
        public DataTable GetORGInfo(string ORG_ID)
        {

            return dal.GetORGInfo(ORG_ID);
        }

        public string GetOrgNameByOrgID(string Org_ID)
        {
            DataTable dt = dal.GetORGInfo(Org_ID);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0]["Org_Name"].ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取所有部门信息
        /// </summary>
        /// <returns></returns>
        public DataTable GetAllOrgData()
        {
           return dal.GetAllOrgData();
        }

        public int IsParentID()
        {
            int ob = dal.IsParentID();
            return ob;
        }

        //读取权限信息
        DALAuth_Role dalRole = new DALAuth_Role ();

        private DataTable dtRole;

        public DataTable DtRole
        {
            get
            {
                if (dtRole == null)
                {
                    dtRole = dalRole.GetAllRoleData();
                }
                return dtRole;
            }
        }

        public void LoadCheckBoxList(System.Web.UI.WebControls.CheckBoxList cbkRole)
        {
            cbkRole.Items.Clear();
            if (DtRole != null && DtRole.Rows.Count > 0)
            {
                foreach (DataRow dr in DtRole.Rows)
                {
                    ListItem listItemCode = new ListItem(dr["Role_Name"].ToString(),dr["Role_ID"].ToString());
                    cbkRole.Items.Add(listItemCode);
                }
            }
        }

        //设置部门权限信息
        DALAuth_Org_Role dalOrgRole = new DALAuth_Org_Role();

        private DataTable dtOrgRole;

        public DataTable DtOrgRole
        {
            get
            {
                if (dtOrgRole == null)
                {
                    dtOrgRole = dalOrgRole.GetAllOrgRoleData();
                }
                return dtOrgRole;

            }
        }

        public void SetCheckBoxList(System.Web.UI.WebControls.CheckBoxList cbkRole, string OrgID)
        {
            if (DtOrgRole != null && DtOrgRole.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrgRole.Select("ORG_ID ='" + OrgID + "'");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                else
                {
                    foreach (ListItem Item in cbkRole.Items)
                    {
                        foreach (DataRow dr in arrDr)
                        {
                            if (dr["Role_ID"].ToString() == Item.Value)
                            {
                                Item.Selected = true;
                            }
                        }
                    }
                }
            }
        }

        public ResultInfo SaveEditDataAndCblData(System.Data.DataSet dsInfo, System.Web.UI.WebControls.CheckBoxList cbkRole)
        {
            ResultInfo result = base.Save(dsInfo);
            if (result.bSuccess == false)
            {
                return result;
            }
            try
            {
                 //取子表，权限信息
                string ORG_ID = dsInfo.Tables[0].Rows[0]["P_Auth_ORG.ORG_ID"].ToString();
                dal.DeleteOldRoleData(ORG_ID);
                List<string> listRole_ID = new List<string>();
                foreach (ListItem Item in cbkRole.Items)
                {
                    if (Item.Selected == true)
                    {
                        listRole_ID.Add(Item.Value);
                    }
                }
                dal.SaveORG_Role(listRole_ID, ORG_ID);
            }
            catch (System.Data.SqlClient.SqlException sqlErr)
            {
                result.bSuccess = false;
                result.ErrorID = sqlErr.Number.ToString();
            }
            catch (System.Exception err)
            {
                result.bSuccess = false;
                result.ErrorDesc = err.Message;
            }
            return result;
        }

        #region 生成树

        DALAuth_Org dal;

        private DataTable dtOrg;

        public DataTable DtOrg
        {
            get
            {
                if (dtOrg == null)
                {
                    dtOrg = dal.GetAllOrgData();
                }
                return dtOrg;
            }
        }

        public void CreateTree(Microsoft.Web.UI.WebControls.TreeView tree)
        {
            if (DtOrg != null && DtOrg.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrg.Select("Parent_ID is null ");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                else
                {
                    DataRow rootDr = arrDr[0];
                    Microsoft.Web.UI.WebControls.TreeNode root = new Microsoft.Web.UI.WebControls.TreeNode();
                    root.ID = rootDr["ORG_ID"].ToString();
                    //root.Text = "[" + rootDr["ORG_Code"] + "]" + rootDr["ORG_Name"].ToString();
                    root.Text = rootDr["ORG_Name"].ToString();
                    string url = "../SystemConfig/Auth_Org.aspx?Parent_ID=" + rootDr["ORG_ID"].ToString();
                    root.NavigateUrl = "../SystemLogin/loadingpage.aspx?Menu_URL=" + HttpContext.Current.Server.UrlEncode(url);
                    tree.Nodes.Add(root);
                    AddChildNode(root,rootDr["ORG_ID"].ToString());
                }
            }

        }

        private void AddChildNode(Microsoft.Web.UI.WebControls.TreeNode root, string parentID)
        {
            if (DtOrg != null && DtOrg.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrg.Select("Parent_ID='" + parentID + "'");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                foreach( DataRow dr in arrDr )
                {
                    Microsoft.Web.UI.WebControls.TreeNode child = new Microsoft.Web.UI.WebControls.TreeNode();
                    child.ID = dr["ORG_ID"].ToString();
                    //child.Text = "[" + dr["ORG_Code"] + "]" + dr["ORG_Name"].ToString();
                    child.Text = dr["ORG_Name"].ToString();
                    string url = "../SystemConfig/Auth_Org.aspx?Parent_ID=" + dr["ORG_ID"].ToString();
                    child.NavigateUrl = "../SystemLogin/loadingpage.aspx?Menu_URL=" + HttpContext.Current.Server.UrlEncode(url);
                    root.Nodes.Add(child);
                    AddChildNode(child, dr["ORG_ID"].ToString());
                }
            }
        }

        #endregion

        #endregion
        #region add by 刘英男 检查单位编号是否唯一
        /// <summary>
        ///  检查单位编号是否唯一
        /// </summary>
        /// <param name="checkOrgCode">所属单位编号</param>
        /// <returns>是，否</returns>
        public bool CheckORG_Code(string checkOrgCode)
        {
            int checkOrg= dal.CheckORG_Code(checkOrgCode);
            if (checkOrg == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region add by 刘英男 检查能否是历史单位
        /// <summary>
        ///  检查能否是历史单位
        /// </summary>
        /// <param name="ORG_ID">所属单位编号</param>
        /// <returns>是，否</returns>
        public bool checkHistoryORG(string ORG_ID)
        {
            int checkOrg = dal.checkHistoryORGInfo(ORG_ID);
            int checkOrgUser = dal.checkHistoryORGUserInfo(ORG_ID);
            if (checkOrg == 0 && checkOrgUser ==0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除组织机构（将机构状态设置为历史状态）
        /// </summary>
        /// <param name="org_ID"></param>
        public void UpdateOrgToHistory(string org_ID)
        {
            this.dal.UpdateOrgToHistory(org_ID);
        }

        /// <summary>
        /// 获取最大的编号
        /// </summary>
        /// <returns></returns>
        public int GetMaxOrgCode()
        {
           return this.dal.GetMaxOrgCode();
        }
        #endregion
    }
}